package com.abe.libcore.base.screen.j;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.abe.libcore.base.screen.OnHandlerListener;
import com.abe.libcore.base.screen.RelayoutTool;

public abstract class AbeJFragment extends BJScreenFragment {
    private int appToast = 0x999;
    protected View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(getLayoutRes(), container, false);
        if (isAutoZoom() && getScale() != 1.0F)
            RelayoutTool.INSTANCE.relayoutViewHierarchy(rootView, getScale());
        initContent();
        return rootView;
    }

    protected abstract int getLayoutRes();

    protected abstract void initContent();

    /**********************************************************************************************/
   protected class BaseHandler extends Handler {
        BaseHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == appToast) {
                Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
            } else {
                if (isImp(AbeJActivity.class, OnHandlerListener.class)) {
                    ((OnHandlerListener) AbeJFragment.this).dispatchHandleMessage(msg);
                }
            }
        }
    }

    protected void toast(String content) {
        if (TextUtils.isEmpty(content)) return;
        localSendMsg(appToast, content);
    }

    protected void localSendMsg(int what, Object obj) {
        getHandler().sendMessage(getMessage(what, obj));
    }

    //获取Message
    protected Message getMessage(int what, Object obj) {
        Message msg = new Message();
        msg.what = what;
        msg.obj = obj;
        return msg;
    }

    //获取Handler
    protected BaseHandler getHandler() {
        return new BaseHandler(Looper.getMainLooper());
    }

    /**
     * 是否实现接口
     *
     * @param a 类
     * @param b 接口
     */
    protected Boolean isImp(Class<?> a, Class<?> b) {
        return b.isAssignableFrom(a);
    }
}
